import pandas as pd
import matplotlib.pyplot as plt
import mplfinance as mpf
import talib
import akshare as ak
# AKSHARE上获取数据  从某天到某天后复权
stock_zh_a_daily_hfq_d = ak.stock_zh_a_daily(symbol="sz002302", start_date="20200101", end_date="20230101", adjust="hfq")

# 获取SZ000002从20150101 to 20200101  后复权
df = stock_zh_a_daily_hfq_d.iloc[:, 0:6]
df.reset_index(inplace = True)
df['date'] = pd.to_datetime(df['date'],format='%Y-%m-%d')

print(df)
df.set_index('date',inplace=True)
df.rename(columns = {0:"Date"})

# mpf.plot(df, type='candle')

my_color = mpf.make_marketcolors(up='red',#上涨时为红色
                                 down='green',#下跌时为绿色
                                 edge='i',#隐藏k线边缘
                                 volume='in',#成交量用同样的颜色
                                 inherit=True)

my_style = mpf.make_mpf_style(gridaxis='both',#设置网格
                           gridstyle='-.',
                           y_on_right=True,
                            marketcolors=my_color)

#计算OBV
df['OBV'] = talib.OBV(df.close,df.volume)
#计算布林带上中下轨
#matype=talib.MA_Type.T3表示用指数移动平均的方法进行平均
df['upper'],df['middle'],df['lower'] = talib.BBANDS(df.close, matype=talib.MA_Type.T3)
#设置要显示的信息
add_plot = [mpf.make_addplot(df[['upper','lower']],linestyle='dashdot'),
            mpf.make_addplot(df['middle'],linestyle='dotted',color='y'),
            mpf.make_addplot(df['OBV'],panel='lower',color='b')]#panel为lower表示在附图中显示


mpf.plot(df,type='candle',
         style=my_style,
         addplot=add_plot,
         volume=True,#展示成交量副图
         figratio=(2,1),#设置图片大小
         figscale=5)